package com.quanshu.exchange.ui.gui.message.chat.emoji;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.util.AttributeSet;

import com.quanshu.exchange.ui.widget.WrapContentHeightViewPager;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.subjects.BehaviorSubject;

public class EmojiconPagerView extends WrapContentHeightViewPager {

    private EmojiViewPagerAdapter adapter;
    private List<EmojiFragment> fragments = new ArrayList<>();

    public BehaviorSubject<EmojiBean> getEmojiDeleteClick() {
        return emojiDeleteClick;
    }

    public BehaviorSubject<EmojiBean> getEmojiClick() {
        return emojiClick;
    }

    private BehaviorSubject<EmojiBean> emojiDeleteClick = BehaviorSubject.create();
    private BehaviorSubject<EmojiBean> emojiClick = BehaviorSubject.create();

    public static final int EMOJI_COLUMN = 8;
    public static final int EMOJI_ROW = 6;

    private Context context;
    public EmojiconPagerView(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    public EmojiconPagerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public void init(FragmentManager fragmentManager) {
        List<EmojiBean> emojicons = EmojiUtil.getEmojiDatas(context);
        if (emojicons != null && emojicons.size() > 0) {
            EmojiFragment fragment;
            for (int i = 0; i < emojicons.size(); i += EMOJI_ROW * EMOJI_COLUMN) {
                List<EmojiBean> tmp;
                if (i + EMOJI_ROW * EMOJI_COLUMN < emojicons.size()) {
                    tmp = emojicons.subList(i, i + EMOJI_ROW * EMOJI_COLUMN);
                } else {
                    tmp = emojicons.subList(i, emojicons.size());
                }
                fragment = EmojiFragment.newInstance(new ArrayList<>(tmp));
                fragment.getEmojiDeleteClick().subscribe(emojicon -> emojiDeleteClick.onNext(emojicon));
                fragment.getEmojiClick().subscribe(emojicon -> emojiClick.onNext(emojicon));
                fragments.add(fragment);
            }
        }
        if (adapter == null) {
            adapter = new EmojiViewPagerAdapter(fragmentManager, fragments);
        }
        setAdapter(adapter);
    }

    public int getPageSize() {
        if (adapter != null) {
            return adapter.getCount();
        }
        return 0;
    }
}
